package be.rivendale.renderer.mk2;

import be.rivendale.renderer.mk2.data.Queue;
import be.rivendale.renderer.mk2.data.Segment;

import java.util.ArrayList;
import java.util.List;

public class ConsumerThread extends Thread {
    private List<Consumer> consumers = new ArrayList<Consumer>();
    private Queue<Segment> resultQueue;

    public ConsumerThread(Queue<Segment> resultQueue) {
        super(ConsumerThread.class.getSimpleName());
        this.resultQueue = resultQueue;
    }

    @Override
    public void run() {
        fireConsumerStarted();
        while(true) {
            Segment segment = resultQueue.take();
            fireSegmentComplete(segment);
            Thread.yield();
        }
    }

    private synchronized void fireSegmentComplete(Segment segment) {
        for (Consumer consumer : consumers) {
            consumer.onSegmentComplete(segment);
        }
    }

    private synchronized void fireConsumerStarted() {
        for (Consumer consumer : consumers) {
            consumer.onConsumerStarted();
        }
    }

    public synchronized void addConsumer(Consumer consumer) {
        consumers.add(consumer);
    }
}
